#include "ThreadPool.hpp"
#include "TaskQueue.hpp"
#include "Thread.hpp"
#include "myThread.hpp"

#include <unistd.h>
#include <iostream>
using std::cout;
using std::endl;

namespace tp{


ThreadPool:: ThreadPool(int que_size,int thread_num )
:_thread_num(thread_num)
,_que_size(que_size)
,_taskque(_que_size)
,_isExit(false){

}
ThreadPool:: ~ThreadPool(){

}

void ThreadPool::start(){
    for(int i = 0; i< _thread_num;++i){
        unique_ptr<Thread> up(new myThread(*this)); 
        _threads.push_back(std::move(up));
    }

    for(auto & th : _threads){
        th->start();
    }
}
void ThreadPool::stop(){
    while(!_taskque.empty()){
        sleep(1);
    }
    _isExit = true;
    _taskque.wakeup();

    for(auto &th: _threads){
        th->join();
    }
}
void ThreadPool::addTask(ElemType ele){
    _taskque.push(ele); 
}
    
void ThreadPool::doTask(){ //作为线程run函数的具体执行内容
    while(!_isExit){
        ElemType ele = _taskque.pop();
        if(ele){
            ele();
        }
    }
}}
